local UIBase = require("view.UIBase")
local ChatView = class("ChatView", UIBase)
local ChatContentCell = require("view.chat.ChatContentCell")
local Vector2 = require("utils.Vector2")
local Vector3 = require("utils.Vector3")

function ChatView:ctor(user)
    self._user = {userId = user.userId, name = user.userName}
    local resource = {
        path = "Prefabs/View/Chat",
        name = "ChatView",
        canvas = 2
    }
    ChatView.super.ctor(self, resource)
end

function ChatView:start()
    self._itemDataList = {}
    self._btnSend.onClick:AddListener(handler(self, self._onBtnSendClick))
    self._listMan:SetTemplate(
        handler(self, self._onItemManUpdate),
        handler(self, self._onValueManChange),
        handler(self, self._onItemManTouch)
    )
    self._chatManList = G_UserData:getChat():getChatList(self._user.userId)
    table.insert(self._chatManList, 1, self._user)
    self._listMan:ReSize(#self._chatManList)
    G_UIUtil.addTouchEvent(self._panelTouch.transform, nil, nil, handler(self, self._onPanelTouchEnd))
    self._chatScroll:SetItemFunc(handler(self, self._chatContentCell))
    self._signalChatMsg = G_SignalManager:add(SignalConst.EVENT_CHAT_MSG_UPDATE, handler(self, self._onEventChatMsg))
    self:_updateChatContent()
end

function ChatView:_chatContentCell(index, parent)
    local startIndex = index + 1
    local msg = self._itemDataList[startIndex]
    if msg then
        local cell = ChatContentCell.new(parent.gameObject, msg)
        return cell:getPanel()
    end
    return nil
end

function ChatView:onDestroy()
    self._signalChatMsg:remove()
    self._signalChatMsg = nil
end

function ChatView:_onPanelTouchEnd()
    self:close()
end

function ChatView:_onItemManUpdate(item, index)
    local startIndex = index + 1
    local data = self._chatManList[startIndex]
    item:updateUI(data, self._user.userId)
end

function ChatView:_onValueManChange()
end

function ChatView:_onItemManTouch(item, data)
    self._user = data
    self._listMan:UpdateUsedCell()
end

function ChatView:_onBtnSendClick()
    local content = self._inputChat.text
    if content ~= "" then
        self._inputChat.text = ""
        G_UserData:getChat():c2sChat(self._user.userId, content)
    end
end

function ChatView:_onEventChatMsg(id, msg)
    local playerId = msg:getPlayerId()
    if playerId == self._user.userId then
        self:_updateChatContent()
    end
end

function ChatView:_updateChatContent()
    self._itemDataList = G_UserData:getChat():getMsgList(self._user.userId)
    self._chatScroll:reloadData()
end

return ChatView
